/*
* Conditions Of Use
*
* This software was developed by employees of the Sigmatrix(Beijing) Corporation.
* This software is provided by sigmatrix as a service and is expressly
* provided "AS IS."  Sigmatrix MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY.  Sigmatrix does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement.
*
*/
package com.sigmatrix.h5.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sigmatrix.h5.dao.WarehouseDao;
import com.sigmatrix.h5.dao.WarehouseStockDao;
import com.sigmatrix.h5.dto.ProductData;
import com.sigmatrix.h5.dto.StockSyncDto;
import com.sigmatrix.h5.dto.WarehouseData;
import com.sigmatrix.h5.enums.ResponseEnum;
import com.sigmatrix.h5.exception.ServiceException;
import com.sigmatrix.h5.request.Request;
import com.sigmatrix.h5.response.Response;
import com.sigmatrix.h5.service.ProductService;
import com.sigmatrix.h5.service.StockService;
import com.sigmatrix.h5.service.common.impl.BaseServiceImpl;
import com.sigmatrix.h5.utils.Cons;
import com.sigmatrix.h5.utils.Utils;

/**
 *@ClassName: StockServiceImpl
 *@Description: 库存
 *@author 
 *@date 2017年9月14日 下午8:50:53
 */
@Service
public class StockServiceImpl extends BaseServiceImpl<WarehouseData> implements StockService {

	/**logger record*/
	private static final Logger LOGGER = LoggerFactory.getLogger(StockServiceImpl.class);
	
	@Autowired
	private transient WarehouseStockDao warehouseStockDao;
	@Autowired
	private transient WarehouseDao warehouseDao;
	@Autowired
	private transient ProductService productService;
	
	
	/**
	 * (non-Javadoc)
	 *@Title: syncList
	 *@Description: 
	 *@see com.sigmatrix.h5.service.StockService#syncList(com.sigmatrix.h5.request.Request)
	 *@author 
	 *@date 2017年9月14日 下午8:51:02
	 */
	@Override
	public Response syncList(final Request request) throws ServiceException {
		try{
			final String eseCode = request.getEnterpriseCode();
			//根据经销商查询仓库
			final List<WarehouseData> warehouseList = 
					warehouseDao.findPartByDealerId(eseCode,request.getUserDealerId());
			if(Utils.isEmpty(warehouseList)){
				LOGGER.info("经销商仓库信息不存在");
				return new Response(ResponseEnum.EXCEPTION.getCode(), "经销商仓库信息不存在");
			}
			//仓库id集合
			final List<Integer> warehouseIdList = new ArrayList<Integer>();
			for (WarehouseData warehouse : warehouseList) {
				warehouseIdList.add(warehouse.getWarehouseId());
			}
			
			//根据仓库查询库存  一个经销商可能有多个仓库
			List<StockSyncDto> stockList = warehouseStockDao.findPartByWarehouseId(eseCode,warehouseIdList);
			if(Utils.isEmpty(stockList)){
				LOGGER.info("经销商仓库没有库存");
				return new Response(ResponseEnum.EXCEPTION.getCode(), "经销商仓库没有库存");
			}
			
			//按照产品对库存记录分组，（一个产品会有多条库存记录）
			Map<Integer,ArrayList<StockSyncDto>> map = new HashMap<Integer,ArrayList<StockSyncDto>>();
			for (StockSyncDto stockDto : stockList) {
				if(map.containsKey(stockDto.getProductId())){
					map.get(stockDto.getProductId()).add(stockDto);
				}else{
					map.put(stockDto.getProductId(), new ArrayList<StockSyncDto>(Arrays.asList(stockDto)));
				}
			}
			//返回的库存明细
			List<StockSyncDto> retStockList = new ArrayList<StockSyncDto>();
			//根据level合并数量
			for (Entry<Integer, ArrayList<StockSyncDto>> entry : map.entrySet()) {
				StockSyncDto retStockDto = new StockSyncDto();
				  //更具id查询产品名称
				final ProductData proDto = productService.findById(entry.getKey(), eseCode);
				if(Utils.isEmpty(proDto)){
					LOGGER.info("产品信息不存在，产品id={}",entry.getKey());
					return new Response(ResponseEnum.EXCEPTION.getCode(), "根据id查询产品，信息不存在");
				}
				retStockDto.setProductCode(proDto.getProductCode());
				retStockDto.setProductId(proDto.getProductId());
				retStockDto.setProductName(proDto.getProductName());
				retStockDto.setPackLevel(Utils.isNotEmpty(proDto.getProductUnit())?new Integer(proDto.getProductUnit()):null);
				retStockDto.setPackUnit(proDto.getPackUnit());
				retStockDto.setSingleLevel(Cons.PACK_LEVEL_ONE);
				retStockDto.setSingleUnit(proDto.getSingleUnit());
				//计算包装数量和单品数量
				int sqNumber = 0; //单品数量
				int number = 0;//包装数量
				for (StockSyncDto stockDto : entry.getValue()) {
					if(Cons.PACK_LEVEL_ONE == stockDto.getLevel()){//单品数据
					  //retStockDto.setSpNumber(Utils.isNotEmpty(stockDto.getNumber())?stockDto.getNumber():0);
						if (Utils.isNotEmpty(stockDto.getNumber())) {
							sqNumber = sqNumber+stockDto.getNumber();
						}
					}else{//包装数量
					  //retStockDto.setNumber(Utils.isNotEmpty(stockDto.getNumber())?stockDto.getNumber():0);
					  if (Utils.isNotEmpty(stockDto.getNumber())) {
						number = number+stockDto.getNumber();
					  }
					}
				}
				retStockDto.setSpNumber(sqNumber);
				retStockDto.setNumber(number);
				retStockList.add(retStockDto);
			}
			return new Response(ResponseEnum.SUCCESS, retStockList);
		} catch (Exception e) {
			throw new ServiceException(e); 
		}
	}
	
	
	public static void main(String[] args) {
		int i = 0;
		for (int j = 0; j <3; j++) {
			i = i+j;
			
		}
		System.err.println(i);
	}

}
